<?php

namespace app\traits;


use app\model\TrendsModel;
use app\model\UserBlacklistModel;
use app\model\UserFollowModel;
use app\model\UserModel;

/**
 * 隐私设置验证
 * @return
 * @author yuncran@126.com
 */
trait PrivacyCheckAuthTrait
{

    /** @var int 缓存时间 */
    private $trends_time = 200;

    /**
     * 需要进行验证的方法
     * @var string[]
     */
    private $action = [
        'addUserTrendsComment', //会员评论
        'addGive', //会员点赞
        'addCollect',    // 会员收藏
    ];

    /**
     * 会员设置鉴权
     * @param $app
     * @return \Exception|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author yuncran@126.com
     */
    public function init($app)
    {

        //需要验证的控制
        if (in_array($app->request->action(), $this->action)) {
            $trends_id = $app->request->param('trends_id');
            $trends = TrendsModel::where(['id' => $trends_id])->cache($this->trends_time)->field('id,user_id')->find()->toArray();
            /** @var  $trends_user 获取发帖人的权限 */
            $trends_user = UserModel::where(['id' => $trends['user_id']])->field(['id', 'is_comment', 'is_give', 'is_collect'])->find();
            //查找发布动态trends会员信息的黑名单
            $userBlacklist = UserBlacklistModel::where('user_id', $trends['user_id'])->column('to_user_id');
            // 查找关注的会员
            $follow = UserFollowModel::where('to_user_id', $trends['user_id'])->column('user_id');

            $list = [
                'addUserTrendsComment' => lang('您没有权限评论'),
                'addGive' => lang('您没有权限点赞'),
                'addCollect' => lang('您没有权限收藏'),
            ];
            if (!empty($userBlacklist) || !empty($follow) || $trends_user['is_comment'] != 0 || $trends_user['is_give'] != 0 || $trends_user['is_collect'] != 0) {
                //黑名单会员除外
                if ($trends_user['is_comment'] == 1 || $trends_user['is_give'] == 1 || $trends_user['is_collect'] == 1) {
                    if (in_array($app->request->uid, $userBlacklist)) {
                        return echoShutDown(lang($list[$app->request->action()]), 1001);
                    }
                }
                //只有关注的人可以评论
                if ($trends_user['is_comment'] == 2 || $trends_user['is_give'] == 2 || $trends_user['is_collect'] == 2) {
                    if (!in_array($app->request->uid, $follow)) {
                        return echoShutDown(lang($list[$app->request->action()]), 1001);
                    }
                }
            }
        }

    }


}